import cv2
import numpy as np


def cv_show(name, img):
    cv2.imshow(name, img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()


rate = 0.35
img1 = cv2.imread('../pictures/1.png', cv2.IMREAD_COLOR)
img1 = cv2.resize(img1, (0, 0), fx=rate, fy=rate)

img2 = cv2.imread('../pictures/2.png', cv2.IMREAD_COLOR)
img2 = cv2.resize(img2, (0, 0), fx=rate, fy=rate)

img3 = cv2.imread('../pictures/3.png', cv2.IMREAD_COLOR)
img3 = cv2.resize(img3, (0, 0), fx=rate, fy=rate)
# cv2.imshow('img2', img2)

# kernel = np.ones((3, 3), np.uint8)

# v1 = cv2.Canny(img1, 0, 255)
# v2 = cv2.Canny(img2, 0, 1)


# imageClone1 = np.zeros((img1.shape[0], img1.shape[1], 1), np.uint8)
# imageClone2 = np.zeros((img2.shape[0], img2.shape[1], 1), np.uint8)

# im1 = cv2.resize(img1, (110, 220))
# im2 = cv2.resize(img2, (110, 220))
# res = np.hstack((img1, img2))
# cv2.imshow('res', res)

# cv_show('img2', img2)

# # 灰度图
ref = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)
# cv_show('img2', ref)

# 二值
# ref = cv2.threshold(ref, 80, 255, cv2.THRESH_BINARY_INV)[1]
# cv_show('img2', ref)


# == start ======
def show_threshold(x):
    global ref
    min = cv2.getTrackbarPos('min', 'test')
    max = cv2.getTrackbarPos('max', 'test')
    print('min:%d, max:%d' % (min, max))
    temp = cv2.threshold(ref, min, max, cv2.THRESH_BINARY_INV)[1]

    cv2.imshow('test', temp)


def show_threshold_tool():
    cv2.namedWindow('test')
    cv2.createTrackbar('min', 'test', 0, 255, show_threshold)
    cv2.createTrackbar('max', 'test', 255, 255, show_threshold)

    while(1):
        k = cv2.waitKey(1) & 0xFF
        if k == 27:
            break


def get_part_img(img):
    width = img.shape[1]
    height = img.shape[0]
    print(img.shape)    # (3840, 2160, 3)

    h1 = int(height/4*3)
    mid_with=256
    w1 = int((width-mid_with)/2)
    w2 = int((width+mid_with)/2)
    temp_part = img[h1:height, w1: w2]
    # cv_show('part', temp_part)
    return temp_part


part = get_part_img(ref)
# cv_show('part', part)

# show_threshold_tool()


# == end ======
# 获取技能栏 边框
# 61 181
temp = cv2.threshold(part, 61, 181, cv2.THRESH_BINARY_INV)[1]
cv_show('temp', temp)

refCnts, hieratchy = cv2.findContours(
    temp.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

cv2.drawContours(temp, refCnts, -1, (0, 0, 255), 3)
print(np.array(refCnts).shape)
# cv_show('temp', temp)


# 销毁窗口
# cv2.destroyAllWindows()
cv2.waitKey(0)
